package com.zhu.tool_test.controller;



import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.util.CollectionUtils;
import com.zhu.tool_test.aop.anno.ResultOpre;
import com.zhu.tool_test.entity.Device;
import com.zhu.tool_test.plugins.ExcleExportAbs;
import com.zhu.tool_test.util.EasyExcelUtil;
import core.Data;
import core.MultipartData;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


import com.alibaba.excel.support.ExcelTypeEnum;


@RestController
@RequestMapping("/api/hello")
@ResultOpre
public class HelloWorldController  {
    private static final Logger log = LogManager.getLogger(HelloWorldController.class);

    @Autowired
    protected HttpServletResponse response;
//    /**
//     * 导入Excel
//     *
//     * @param file
//     * @author Lynch
//     */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    @ResponseBody
//    public ResponseWrapper<?> importExcel(@RequestParam(value = "uploadFile", required = false) MultipartFile file) {
//        try {
//            List<ExcelModel> excelModelList = EasyExcelUtil.readExcelWithModel(file.getInputStream(), ExcelModel.class, ExcelTypeEnum.XLSX);
//            return ResponseWrapper.ok(excelModelList);
//        } catch (IOException e) {
//            log.error("Excel导入失败", e);
//        }
//
//        return ResponseWrapper.ok();
//    }
//
//    /**
//     * 导出Excel
//     *
//     * @param response
//     * @author Lynch
//     */
//    @RequestMapping(value="/writeExcel")　  @ResponseBody
//    public ResponseWrapper<String>writeExcel(HttpServletResponse response){
//        //初始化模拟数据
//        List<ExcelModel> excelModelList = new ArrayList<>();
//        for (int i = 0; i < 700; i++) {
//            ExcelModel excelModel = new ExcelModel();
//            excelModel.setAddress("address" + i);
//            excelModel.setAge(i + "");
//            excelModel.setEmail("email" + i);
//            excelModel.setHeigh("heigh" + i);
//            excelModel.setLast("last" + i);
//            excelModel.setName("name" + i);
//            excelModel.setSax("sax" + i);
//            excelModelList.add(excelModel);
//        }
//
//        return writeExcel("abc", excelModelList);
//    }

    /**
     * 导出Excel工具类
     *
     * @param fileName 导出文件名，不填默认"abbot.xlsx"
     * @param data 导出数据
     * @author Lynch
     */
    protected Data writeExcel(String fileName, List<? extends BaseRowModel> data) {
        try {
            if(CollectionUtils.isEmpty(data)) {
                log.warn("Excel导出数据为空");
                return new MultipartData().include("ERROR_COLLECTION_EMPTY", "Excel导出数据为空");
            }

            if(StringUtils.isEmpty(fileName)) {
                fileName = "abbot.xlsx";
            }

            String filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setHeader("Content-disposition", String.format("attachment; filename=%s.xlsx", filename));

            // 将文件输出
            EasyExcelUtil.writeExcelWithModel(response.getOutputStream(), data, data.get(0).getClass(), ExcelTypeEnum.XLSX);
            data = null;
        } catch (Exception e) {
            log.error("Excel导出失败", e);
            return new MultipartData().include("falie","Excel导出失败");
        }

        return new MultipartData().include("sucess","Excel导出成功");
    }

    @PostMapping("/download")
    public Data download(HttpServletResponse response,String fileName,@RequestBody String headJson) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        //String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcelUtil.dynamicHeadWrite(response.getOutputStream(),EasyExcelUtil.jsonHead(headJson),EasyExcelUtil.jsonBody(),ExcelTypeEnum.XLSX);
        return new Data().include("code","200");
    }

    @PostMapping("/downloadTest")
    public Data downloadTest(HttpServletResponse response,String fileName,@RequestBody String headJson) throws IOException {

        // 获取表格数据
        Device device = new Device();
        List<Device> devices = device.selectAll();
        List<MultipartData> dataList = MultipartData.trans2MultipartData(devices);

        ExcleExportAbs.dynamicWrite(response,fileName,dataList,headJson);
        return new Data().include("code","200");
    }

    @GetMapping("/aop")
    @ResultOpre
    public MultipartData aopTest(){
        MultipartData data = new MultipartData().include("data", "111");
        return data;
    }

    @GetMapping("/advice/test")
    public MultipartData adviceTest(){
        MultipartData data = new MultipartData().include("data", new ArrayList<Integer>(){{}});
        data.include("msg","操作成功");
        data.include("code","200");
        return data;
    }

    @PostMapping("/advice/test")
    public MultipartData advicePostTest(){
        MultipartData data = new MultipartData().include("data", new ArrayList<Integer>(){{}});
        data.include("msg","操作成功");
        data.include("code","200");
        return data;
    }

    @GetMapping("/advice/exception/test")
    public MultipartData adviceExTest(){

        int i = 1/0;

        MultipartData data = new MultipartData().include("data", new ArrayList<Integer>(){{}});
        data.include("msg","操作成功");
        data.include("code","200");
        return data;
    }


}
